//
//  SCNHomeModels.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/3/13.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import UIKit
import Kingfisher

class HomeBannersView: UIView {

    fileprivate var contentView: UICollectionView!

    fileprivate var pageControl: UIPageControl!

    fileprivate var timer: DispatchSourceTimer?
    
    fileprivate var layout: UICollectionViewFlowLayout!
    
    typealias headerAction = (String) -> Void
    // 给闭包声明变量
    var headeractionClosures: headerAction?

    var banners: Array<SCNHomeBannerModels>!{
        didSet{
            
            self.configurationData()
        }
        
    }


    fileprivate var currentIndexPath: IndexPath?

    public override init(frame: CGRect) {
        super.init(frame: frame)

        self.configurationUI()

//        self.configurationData()

    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        layout.itemSize = self.frame.size
    }

    deinit {
        self.stopTimer()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func configurationUI() {

        layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.horizontal
        
        layout.minimumLineSpacing = 0

        contentView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        contentView.isPagingEnabled = true
        contentView.bounces = false
        contentView.showsVerticalScrollIndicator = false
        contentView.showsHorizontalScrollIndicator = false
        contentView.delegate = self
        contentView.dataSource = self
        contentView.backgroundColor = .lightGray
        self.addSubview(contentView)
        
        contentView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }

        contentView.register(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "bannerItem")

        pageControl = UIPageControl()
        pageControl.pageIndicatorTintColor = UIColor.red
        pageControl.currentPageIndicatorTintColor = UIColor.blue

        self.addSubview(pageControl)
    }

    private func configurationData() {

        guard banners.count > 0 else {
            return
        }
        
//        pageControl.numberOfPages = banners.count
//        let size = pageControl.size(forNumberOfPages: banners.count)
//        pageControl.frame = CGRect(x: contentView.center.x - size.width / 2, y: contentView.center.y * 1.5, width: size.width, height: size.height)

        contentView.reloadData()

        currentIndexPath = NSIndexPath(item: banners.count * 2, section: 0) as IndexPath

        contentView.scrollToItem(at: currentIndexPath!, at: .left, animated: false)

        weak var weakSelf = self
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            if self.banners.count > 1 {
                weakSelf?.startTimer()
            }
        }


    }

    // MARK: - 定时器

    func startTimer() {

        weak var weakSelf = self
        

        let queue = DispatchQueue(label: "com.shoucainu8", attributes: .concurrent)
        timer = DispatchSource.makeTimerSource(flags: [], queue: queue)

        timer?.scheduleRepeating(deadline: .now() + 0.5, interval: .seconds(3), leeway: .seconds(1))

        timer?.setEventHandler {

            DispatchQueue.main.async(execute: {
                weakSelf?.loadTimer()
            })

        }

        timer?.resume()
    }

    func stopTimer() {
        
        
        timer?.cancel()
        timer = nil
    }

    func loadTimer() {


        guard let currentIndexPath = currentIndexPath else {
            return
        }

        pageControl.currentPage = currentIndexPath.item % banners.count



        self.currentIndexPath = IndexPath(item: currentIndexPath.item + 1, section: 0)
        if currentIndexPath.item > banners.count * 5 {
            self.currentIndexPath = IndexPath(item: banners.count * 2, section: 0)
        }else {
            contentView.scrollToItem(at: currentIndexPath, at: .left, animated: true)
        }
        



        if self.currentIndexPath?.item == banners.count * 4  || self.currentIndexPath?.item == banners.count  {
            //如果是最后一个图片，回到第一部分的最后一张图片
            let newIndexPath = IndexPath(item: banners.count * 2 - 1, section: 0)

            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.contentView.scrollToItem(at: newIndexPath, at: .left, animated: false)
            }
            self.currentIndexPath = IndexPath(item: banners.count * 2 , section: 0)
        }





    }

}

extension HomeBannersView: UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {


    // MARK: - UICollectionView

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let tmp = banners {
            return tmp.count * 5
        }else {
            return 0
        }
        
        
    }


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let item = collectionView.dequeueReusableCell(withReuseIdentifier: "bannerItem", for: indexPath)
//        let red = CGFloat(arc4random_uniform(255)) / CGFloat(255.0)
//        let green = CGFloat(arc4random_uniform(255)) / CGFloat(255.0)
//        let blue = CGFloat(arc4random_uniform(255)) / CGFloat(255.0)
//        let colorRun = UIColor.init(red: red, green: green, blue: blue, alpha: 1)
        let imageView = UIImageView()
        imageView.backgroundColor = .lightGray
//        let number = UILabel()
//        number.text = "\(indexPath.item)"
//        imageView.addSubview(number)
//        number.sizeToFit()

//        let colorArray = [UIColor.red,UIColor.yellow,UIColor.green]

        let bannerObj = banners[indexPath.item % banners.count]

        let img = bannerObj.imageUrl ?? "not image url"
        imageView.kf.setImage(with: URL(string:img))
//        imageView.image = UIImage(named:img)
//        imageView.backgroundColor = .lightGray
        imageView.contentMode = UIViewContentMode.redraw
        item.backgroundView = imageView



        return item
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        defer {
            collectionView.deselectItem(at: indexPath, animated: true)
        }
        
        let model = banners[indexPath.item % banners.count]
        
        let detail = model.detailsUrl
        
        if let tmp = detail {
            if tmp != "" {
                headeractionClosures?(tmp)
            }
            
        }
        
        
    }


    // MARK: - UIScrollView

    /// 开始滑动的时候
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        stopTimer()
    }

    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {

    }


    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        let index = scrollView.contentOffset.x / contentView.frame.size.width

        let lroundfIndex = lroundf(Float(index))

//        print(lroundfIndex)
        let temp = NSIndexPath(item: lroundfIndex, section: 0) as IndexPath

        pageControl.currentPage = lroundfIndex % banners.count

        currentIndexPath = temp

        contentView.scrollToItem(at: currentIndexPath!, at: .left, animated: true)

        if (self.currentIndexPath?.item)! <= banners.count - 2 || (self.currentIndexPath?.item)! >= banners.count * 4{
            printLog("滑动过快，会出现跳过阈值而导致判断不准确")
            let newIndexPath = IndexPath(item: banners.count * 2 - 1, section: 0)
            
            
            self.contentView.scrollToItem(at: newIndexPath, at: .left, animated: false)
            
            
            self.currentIndexPath = IndexPath(item: banners.count * 2 , section: 0)
        }

        if (self.currentIndexPath?.item)! >= banners.count * 4 - 1  || self.currentIndexPath?.item == banners.count - 1  {
            //如果是最后一个图片，回到第一部分的最后一张图片
//            print("\(currentIndexPath) - - \(pageControl.currentPage)")

            let newIndexPath = IndexPath(item: banners.count * 2 - 1, section: 0)

            self.contentView.scrollToItem(at: newIndexPath, at: .left, animated: false)

            self.currentIndexPath = IndexPath(item: banners.count * 2 , section: 0)
        }

        startTimer()
    }


}
